import random
# from woniuatm_3.utility import Utility as Tools

class User:

    login_username = ''

    def __init__(self):
        self.utility = None    # 将Utility类的实例赋值给User类的实例变量utility
        self.menu = None

    def reg(self):
        username = self.input_username()
        password = self.input_password()
        phone = self.input_phone()

        balance = random.randrange(1000, 5000, 100)
        sql = "insert into user(username, password, balance, phone) values('%s', '%s', %d, '%s')" % (username, password, balance, phone)

        self.utility.update_data(sql)

        self.menu.start_menu()


    def login(self):
        from woniuatm_3.utility import Utility
        from woniuatm_3.menu import Menu
        self.menu = Menu()
        self.utility = Utility()
        username = input("请输入用户名[登录]：")
        password = input('请输入密码[登录]：')
        if self.check_user(username):
            sql = "select password from user where username='%s'" % username
            result = self.utility.query_one(sql)
            if result != None and result[0] == password:
                print("恭喜你，登录成功.")
                User.login_username = username
                self.menu.main_menu()
            else:
                print("抱歉，密码输入错误.")
        else:
            print("抱歉，登录用户名不存在.")


    def input_username(self):
        username = input("请输入用户名[注册]：")
        if self.check_user(username):
            print("你注册的用户名已经存在.")
            return self.input_username()
        else:
            return username


    def input_password(self):
        password = input('请输入密码[注册]：')
        if len(password) < 5:
            print("你输入的密码过短.")
            return self.input_password()
        else:
            return password


    def input_phone(self):
        phone = input('请输入电话号码[注册]：')
        if not self.check_phone(phone):
            print("你注册的电话号码不正确.")
            return self.input_phone()
        else:
            return phone


    def check_user(self, username):
        sql = "select username from user where username='%s'" % username
        result = self.utility.query_one(sql)
        if result != None:
            return True
        else:
            return False


    def check_phone(self, phone):
        if phone.isnumeric():
            if len(phone) != 11:
                return False
            else:
                return True
        else:
            return False



if __name__ == '__main__':
    user = User()
    # print(user.check_user('woniu'))       # 先对check_user方法进行单元测试
    user.reg()
    # user.login()
